<template>
  <wd-toast />
  <view class="poem-list-container">
    <wd-search
      v-model="queryString"
      @search="handleSearchInput"
      @clear="handleClearSearch"
      @change="handleSearchInput"
      placeholder="输入作者或诗名搜索"
      hide-cancel
      custom-class="search-box"
    />

    <!-- 诗歌列表区域 -->
    <scroll-view
      ref="scrollRef"
      scroll-y
      class="scroll-wrapper"
      :style="{ 'padding-top': searchBoxHeight + 'px' }"
      @scrolltolower="handleScrollToLower"
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
    >
      <!-- Boss直聘风格诗歌列表 -->
      <view class="boss-style-list">
        <view
          v-for="(item, index) in processedList"
          :key="item.id || index"
          class="boss-poem-card"
          @click="handlePoemClick(item)"
        >
          <!-- 左侧装饰线 -->
          <view class="card-decoration"></view>

          <view class="card-content">
            <!-- 标题区域 -->
            <view class="card-header">
              <rich-text class="title" :nodes="highlightText(item.title)"></rich-text>
              <view class="tags">
                <!-- 收藏状态标签 -->
                <text v-if="item.isFavorite === '1'" class="tag favorite-tag">已收藏</text>

                <!-- 诗歌类型标签 -->
                <text v-if="item.collection" class="tag">
                  {{ item.collection }}
                </text>
              </view>
            </view>

            <!-- 作者信息 -->
            <rich-text
              class="author"
              :nodes="highlightText(`${item.author} · ${item.dynasty}`)"
            ></rich-text>

            <!-- 诗歌内容预览 -->
            <view class="preview-content">
              <view v-for="(line, i) in item.content.slice(0, 2)" :key="i" class="content-line">
                <rich-text :nodes="highlightText(line)"></rich-text>
              </view>
            </view>

            <!-- 底部信息栏 -->
            <view class="card-footer">
              <view class="meta-info">
                <!-- 诗歌行数 -->
                <text class="meta-item">{{ item.content.length }}行</text>

                <!-- 作者作品数量 -->
                <text v-if="item.poetryCount" class="divider">|</text>
                <text v-if="item.poetryCount" class="meta-item">{{ item.poetryCount }}个作品</text>
              </view>

              <!-- 收藏按钮 -->
              <view
                v-if="showFavorite"
                class="favorite-btn"
                :class="{ favorited: item.isFavorite === '1' }"
                @click.stop="toggleFavorite(item, index)"
              >
                <wd-icon :name="item.isFavorite === '1' ? 'star-on' : 'star'" size="20" />
                <text>{{ item.isFavorite === '1' ? '已收藏' : '收藏' }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <view class="loader"></view>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 无更多数据提示 -->
      <view v-if="showNoMore" class="no-more">
        <text>已经到底啦~</text>
      </view>
    </scroll-view>

    <!-- 分页控件 -->
    <view v-if="showPagination" class="pagination">
      <wd-pagination
        v-model="currentPage"
        :page-size="pageSize"
        :total="total"
        @change="handlePageChange"
        show-icon
      />
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import { favoriteManager } from '@/service/poem/favorite'
import type { ToggleFavoriteItem } from '@/api/favorite.typing'
import { debounce } from 'lodash-es'
import type { PoemPageItem, PageResult } from '@/api/poem.typings'
import { http } from '@/utils/http'
import { useAuthHeaders } from '@/utils/token'
import { useToast } from 'wot-design-uni'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL
const toast = useToast()

const scrollRef = ref<HTMLElement | null>(null)

// 定义组件 Props
const props = defineProps({
  apiPath: { type: String, required: true },
  requestParams: { type: Object, default: () => ({}) },
  initialPage: { type: Number, default: 1 },
  pageSize: { type: Number, default: 10 },
  infiniteScroll: { type: Boolean, default: true },
  showPagination: { type: Boolean, default: false },
  dataProcessor: { type: Function, default: (data: any) => data },
  showFavorite: { type: Boolean, default: true },
})

// 定义 emit 事件
const emit = defineEmits(['load-success', 'load-error'])

// 响应式状态
const currentPage = ref(props.initialPage)
const total = ref(0)
const processedList = ref<PoemPageItem[]>([])
const loading = ref(false)
const scrollTop = ref(0)
const queryString = ref('')
const searchBoxHeight = ref(0)

// 计算属性
const showNoMore = computed(() => {
  return (
    !loading.value &&
    processedList.value.length > 0 &&
    currentPage.value * props.pageSize >= total.value
  )
})

// 生命周期钩子
onMounted(() => {
  loadData()
  const query = uni.createSelectorQuery()
  query
    .select('.search-box')
    .boundingClientRect((data: any) => {
      if (data) searchBoxHeight.value = data.height
    })
    .exec()
})

// 监听 requestParams 变化
watch(
  () => props.requestParams,
  () => {
    refreshData()
  },
  { deep: true },
)

// 核心数据加载方法
const loadData = async (isReset = false) => {
  if (loading.value) return

  loading.value = true
  try {
    const requestParams = {
      ...props.requestParams,
      pageNum: currentPage.value,
      pageSize: props.pageSize,
      queryString: queryString.value.trim(),
    }
    const res = await http.get<PageResult<PoemPageItem>>(
      API_BASE_URL + props.apiPath,
      requestParams,
      useAuthHeaders(),
    )

    if (res.code === 200) {
      const processed = props.dataProcessor(res.data.list).map((item: any) => ({
        ...item,
        __animate: true,
      }))

      processedList.value = isReset ? processed : [...processedList.value, ...processed]
      total.value = res.data.total
      emit('load-success', { list: processedList.value, total: total.value })
    } else {
      toast.error(`加载诗歌列表数据失败:${res.msg}`)
    }
  } catch (error) {
    emit('load-error', error)
    toast.error('加载诗歌列表数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理方法（带防抖）
const handleSearchInput = debounce(() => {
  currentPage.value = props.initialPage
  processedList.value = []
  loadData(true)
}, 500)

// 清空搜索
const handleClearSearch = () => {
  queryString.value = ''
  currentPage.value = 1
  processedList.value = []
  loadData(true)
}

// 高亮文本处理
const highlightText = (text: string) => {
  if (!queryString.value || !text) return text

  const escapedQuery = queryString.value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  const regex = new RegExp(`(${escapedQuery})`, 'gi')

  return text
    .split(regex)
    .map((part, index) => {
      return index % 2 === 1 ? `<span class="highlight">${part}</span>` : part
    })
    .join('')
}

// 分页变化处理
const handlePageChange = async (page) => {
  currentPage.value = page.value
  await loadData(true)
  nextTick(() => {
    scrollToTop()
  })
}

// 滚动到底部加载更多
const handleScrollToLower = () => {
  if (props.infiniteScroll && !showNoMore.value) {
    currentPage.value++
    loadData()
  }
}

// 重置数据
const refreshData = () => {
  currentPage.value = props.initialPage
  processedList.value = []
  loadData(true)
}

// 滚动到顶部
const scrollToTop = () => {
  uni.pageScrollTo({
    scrollTop: 0,
    duration: 300,
  })
}

// 点击诗词
const handlePoemClick = (item: PoemPageItem) => {
  uni.navigateTo({
    url: `/pages/poem/poem-detail?id=${item.id}`,
  })
}

// 收藏切换
const toggleFavorite = async (item: PoemPageItem, index: number) => {
  const favoriteItem: ToggleFavoriteItem = {
    id: item.id,
    isFavorite: item.isFavorite,
  }
  const currentStatus = item.isFavorite
  const success = await favoriteManager.toggleFavorite(favoriteItem)
  if (success) {
    item.isFavorite = currentStatus === '1' ? '0' : '1'
    toast.show({ msg: currentStatus === '1' ? '已加入收藏' : '已取消收藏', duration: 2000 })
  } else {
    item.isFavorite = currentStatus
    toast.error({ msg: '收藏失败，请检查网络后重试', duration: 2000 })
  }
}
</script>

<style lang="scss">
.poem-list-container {
  min-height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  padding-bottom: 20rpx;

  .scroll-wrapper {
    flex: 1;
    padding: 20rpx 24rpx !important;
    height: calc(100vh - 120rpx);
  }

  .pagination {
    position: sticky;
    bottom: 0;
    background: #fff;
    padding: 20rpx;
    border-top: 1rpx solid #eee;
    box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 100;
  }
}

/* Boss风格列表 */
.boss-style-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.boss-poem-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx 32rpx 32rpx 0;
  box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
  display: flex;

  /* 悬停效果 */
  &:active {
    background-color: #f9f9f9;
    transform: translateY(2rpx);
  }

  .card-decoration {
    width: 8rpx;
    background: #4a90e2;
    margin-right: 24rpx;
    border-radius: 0 8rpx 8rpx 0;
  }
}

/* 卡片内容 */
.card-content {
  flex: 1;
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;

  .title {
    font-size: 38rpx !important;
    font-weight: 700;
    color: #333;
    line-height: 1.4;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }

  .tags {
    display: flex;
    gap: 12rpx;

    .tag {
      background: rgba(74, 144, 226, 0.1);
      color: #4a90e2;
      padding: 4rpx 16rpx;
      border-radius: 6rpx;
      font-size: 24rpx;
      font-weight: 500;
    }
  }
}

/* 作者信息 */
.author {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 24rpx;
  line-height: 1.5;
}

/* 预览内容 */
.preview-content {
  margin-bottom: 24rpx;

  .content-line {
    font-size: 30rpx;
    line-height: 1.6;
    color: #555;
    margin-bottom: 12rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
}

/* 卡片底部 */
.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16rpx;
  border-top: 1rpx solid #eee;

  .meta-info {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .meta-item {
      font-size: 24rpx;
      color: #999;
    }

    .divider {
      color: #ddd;
    }
  }

  .favorite-btn {
    display: flex;
    align-items: center;
    gap: 8rpx;
    padding: 6rpx 20rpx;
    border-radius: 30rpx;
    background: #f0f0f0;
    color: #666;
    font-size: 26rpx;

    &.favorited {
      background: rgba(255, 184, 0, 0.1);
      color: #ffb800;
    }
  }
}

/* 搜索框样式优化 */
.search-box {
  position: relative;
  padding: 20rpx 30rpx !important;
  background: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  z-index: 100;
}

/* 高亮样式 */
.highlight {
  color: #ff5722;
  font-weight: bold;
  background: rgba(255, 87, 34, 0.1);
  padding: 0 8rpx;
  border-radius: 4rpx;
}

/* 加载状态 */
.loading-state {
  padding: 40rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;

  .loader {
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid #eee;
    border-top-color: #4a90e2;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  .loading-text {
    color: #666;
    font-size: 28rpx;
  }
}

.no-more {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}

/* 动画 */
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 响应式布局 */
@media (min-width: 768px) {
  .boss-style-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24rpx;
  }
}

@media (min-width: 1024px) {
  .boss-style-list {
    grid-template-columns: repeat(3, 1fr);
  }
}
</style>
